//
//  JXHOAuthViewController.swift
//  JXHSinaWeiBo
//
//  Created by juxiaohui on 16/10/19.
//  Copyright © 2016年 juxiaohui. All rights reserved.
//

import UIKit
import SVProgressHUD

class JXHOAuthViewController: UIViewController {

    // MARK: - 属性
    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        ///UI
        setupNavBar()
        
        loadPage()
    
//        webView.loadRequest(URLRequest.init(url: URL.init(string: "http://www.baidu.com")!))
    }
    
    
    func loadPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        guard  let url = URL.init(string: urlString) else{
            return
        }
        let request = URLRequest.init(url: url)
        
        webView.loadRequest(request)
    }
}

// MARK: - WebView代理方法
extension JXHOAuthViewController : UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
    
    //准备加载某个页面会执行该方法
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url else{
            return true
        }
        
        let urlString = url.absoluteString
        
        guard urlString.contains("code=") else {
            return true
        }
        
        let codeArr = urlString.components(separatedBy: "code=")
        
        let code = codeArr.last!
        
        loadAccessToken(code: code)
        
        return false
    }
}

// MARK: - 网络请求
extension JXHOAuthViewController {

    func loadAccessToken(code : String) {
        
        JXHNetWorkTools.shareInstance.loadAccessToken(code: code) { (response, error) in
         
            if error != nil {
                
                print(error)
                return
            }
            
            guard response != nil else {
                
                return
            }
            
            let accont = JXHUserAccontModel.init(dic: response as! [String : Any])
            
            self.loadUserInfo(accont: accont) //闭包里面调用当前对象的方法self.调用
            
        }
    }
}

extension JXHOAuthViewController {

    func loadUserInfo(accont : JXHUserAccontModel) {
        
        guard let access_token = accont.access_token else {
            return
        }
        
        guard let uid = accont.uid else {
            return
        }
        
        JXHNetWorkTools.shareInstance.loadUserInfo(access_token: access_token, uid: uid) { (result, error) in
            
            if error != nil {
                return
            }
            
            guard let userInfo = result else {
                return
            }
            
            print(result)
            
            accont.screen_name  = userInfo["screen_name"] as? String
            accont.avatar_large = userInfo["avatar_large"] as? String
            
            /// 登陆成功将userInfo本地化存储
            
            var accontPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
           accontPath = (accontPath as NSString).appendingPathComponent("accont.plist")
    
            print(accontPath)
        
            NSKeyedArchiver.archiveRootObject(accont, toFile: accontPath)
            
            JXHUserAcccountTool.shareInstance.accont = accont
            
            self.dismiss(animated: false, completion: {
              
                UIApplication.shared.keyWindow?.rootViewController = JXHWelcomeViewController()
            })
        }
    }
}



// MARK: - 设置UI界面
extension JXHOAuthViewController {

    func setupNavBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "关闭", style: .plain, target: self, action: #selector(JXHOAuthViewController.leftItemClick))
         navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "填充", style: .plain, target: self, action: #selector(JXHOAuthViewController.rightItemClick))
        navigationItem.title = "登陆界面"
    }
}

// MARK: - 时间监听
extension JXHOAuthViewController {

    func leftItemClick() {
        
        dismiss(animated: true, completion: nil)
    }
    
    func rightItemClick() {
        //1.书写js代码
        
        let jsCode = "document.getElementById('userId').value = '15002103667';document.getElementById('passwd').value = 'juxiaohui123.';"

        webView.stringByEvaluatingJavaScript(from: jsCode)
    }
}
